#!/usr/bin/env python

import re
import subprocess
import os.path as path
import sys
from sh import sh

def getSdkVersion(apkPath):
    def extractVersionNumber(SdkVersionStr):
        return int(SdkVersionStr.split(")")[-1], 16)

    aapt_info_lines = sh("aapt list -a {}".format(apkPath), echo=False).split("\n")
    # print aapt_info_lines
    SdkVersionLines = map(lambda x:x.strip(), filter(lambda x:x.find("SdkVersion")>-1, aapt_info_lines))
    # print SdkVersionLines
    targetSdkVersion = filter(lambda x:x.find("target")>-1, SdkVersionLines)
    if targetSdkVersion:
        return extractVersionNumber(targetSdkVersion[0])
    maxSdkVersion = filter(lambda x:x.find("max")>-1, SdkVersionLines)
    if maxSdkVersion:
        return extractVersionNumber(maxSdkVersion[0])
    minSdkVersion = filter(lambda x:x.find("min")>-1, SdkVersionLines)
    if minSdkVersion:
        return extractVersionNumber(minSdkVersion[0])

def getPackageName(apkPath):
    aapt_output = sh("aapt dump badging {}".format(apkPath), echo=False)
    pkgNameList = re.findall(r"package: name='(.*?)'", aapt_output)
    # print re.findall(r"package:.*", aapt_output)
    if pkgNameList:
        return pkgNameList[0]

if __name__=="__main__":
    target = sys.argv[1]

    if path.isfile(target):
        print getPackageName(target)
        print getSdkVersion(target)
